Invariant Functor
#cats
#型クラス
概要
mapとcontramapを組み合わせたものがimap
imapは、双方向の変換を表すデータ型に対してのみ意味がある
If map generates new type class instances by appending a function to a chain, and contramap generates them by prepending an operation to a chain, imap generates them via a pair of bidirectional transformations.
エンコードとデコードが定義できるような型クラスインスタンス
条件
imap
def imap[A, B](fa: F[A])(f: A => B)(g: B => A): F[B]
例
Play JSON’s Format
scodec’s Codec
Scala
code:scala
trait Invariant[F_] { self =>
def imapA, B(fa: FA)(f: A => B)(g: B => A): FB
}
code:scala
trait CodecA { self =>
def encode(value: A): String
def decode(value: String): A
def imapB(dec: A => B, enc: B => A): CodecB = {
new CodecB {
def encode(value: B): String =
self.encode(enc(value))
def decode(value: String): B =
dec(self.decode(value))
}
}
}
encodeはShowと同じ